//
//  ShareSettingViewController.m
//  YinHang
//
//  Created by idea on 14-9-24.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "ShareSettingViewController.h"
#import "CatShareListService.h"
#import "CatSharePageInfo.h"

@interface ShareSettingViewController ()<UITableViewDataSource,UITableViewDelegate,CatShareListServiceDelegate,ASIHTTPRequestDelegate,UIAlertViewDelegate>{
    UITableView *_tableView;
    
    
    __weak IBOutlet UILabel *tNameLabel;
    __weak IBOutlet UIButton *kaiTongModelBtn;
 
    __weak IBOutlet UIButton *editBtn;
    __weak IBOutlet UIButton *deleteSelecteBtn;
    NSMutableArray *zhanghaoMArr;
    NSMutableArray *recordDeleteBtn;
    NSMutableArray *recordDeleteBtn1;
    NSInteger j;//防止tag混乱
    UITableViewCell *cell;
    NSInteger jishurow;//计数
    NSInteger a;//计数删除cell
    
    //zyz
    NSMutableDictionary *recordDic;//记录状态
    __weak IBOutlet UITextField *userZhanghaoTF;
    
    CatShareListService *catShareService;
    
    ASIFormDataRequest *addRequest;//开通请求
    ASIFormDataRequest *delRequest;//删除请求
    
    //参数
    NSString *ids;
    NSString *action;
    NSDictionary *paramsDict;
    
    MBProgressHUD *postHud;
    
    //状态控制
    NSString *state;
    UIAlertView *alert;
}

@end

@implementation ShareSettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //初始状态
    state = @"编辑";
    ids = @"";
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"板块共享设置";
    //返回
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    
    recordDic = [NSMutableDictionary dictionary];//初始化状态数组
    
    [self setUI];
    zhanghaoMArr=[NSMutableArray arrayWithObjects:@"用户账号1", nil];
    recordDeleteBtn=[[NSMutableArray alloc]init];
    recordDeleteBtn1=[[NSMutableArray alloc]init];
    j=12345;
    a=0;
    
    //设置两个btn属性
    kaiTongModelBtn.layer.cornerRadius=5.0;
     kaiTongModelBtn.layer.borderColor=[UIColor grayColor].CGColor;
    kaiTongModelBtn.layer.borderWidth=1;
    [kaiTongModelBtn setBackgroundColor:APP_COLOR];
    
    deleteSelecteBtn.layer.cornerRadius=5.0;
     deleteSelecteBtn.layer.borderColor=[UIColor grayColor].CGColor;
    deleteSelecteBtn.layer.borderWidth=1;
    [deleteSelecteBtn setBackgroundColor:APP_COLOR];
    
    editBtn.layer.cornerRadius=5.0;
    editBtn.layer.borderColor=[UIColor grayColor].CGColor;
    editBtn.layer.borderWidth=1;
    [editBtn setBackgroundColor:APP_COLOR];
    
    [_tableView setBackgroundColor:[UIColor whiteColor]];
    
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getDate];
    [self setupRefresh];
    [_tableView headerBeginRefreshing];
}
#pragma mark - Custom Method
//获取数据
-(void)getDate{
    catShareService = [[CatShareListService alloc]init];
    //linkarr = linkService.pageInfo.dataArr;
    catShareService.delegate = self;
    
}
/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 刷新表格
    if (catShareService.isQuery ||![Constants isExistenceNetwork]) {
        [_tableView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView headerEndRefreshing];
        return;
    }
    
    // 下拉刷新 （请求第一页数据）
    
    // 每次必须重置下 否则会数据混乱
    catShareService.pageInfo.pageno = @"1";
    [catShareService pageQueryWithSelectedIndex:_mid selectedTid:_tid];
}

- (void)footerRereshing
{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView footerEndRefreshing];
        
        return;
    }
    
    // 如果正在查询 或 没有更多数据了
    //    NSLog(@"%i",linkService.isQuery);
    //    NSLog(@"%i",linkService.pageInfo.hasMoreData);
    if (catShareService.isQuery || !catShareService.pageInfo.hasMoreData) {
        // 2. 1秒后刷新表格UI
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [_tableView footerEndRefreshing];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"没有更多数据了";
            [hud hide:YES afterDelay:1];
        });
        
        catShareService.pageInfo.hasMoreData = YES;
        
        return;
    }
    
    // 如果还有更多数据 请求下一页
    [catShareService.pageInfo nextPage];
    [catShareService pageQueryWithSelectedIndex:_mid selectedTid:_tid];
}


-(void)setUI{

    tNameLabel.text = _tName;
    _tableView=[[UITableView alloc]init];
    if (IPHONE5) {
        _tableView.frame=CGRectMake(70, 180, self.view.frame.size.width - 100, 230);
    }else{
     _tableView.frame=CGRectMake(70, 160, self.view.frame.size.width - 100, 170);
    }
    _tableView.backgroundColor=[UIColor clearColor];
    _tableView.dataSource=self;
    _tableView.delegate=self;
    _tableView.rowHeight=30;
    
    //[_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:_tableView];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - TableViewDelegate Method

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //return zhanghaoMArr.count;
    if (catShareService.pageInfo.dataArr.count != 0) {
        return catShareService.pageInfo.dataArr.count;
    }else{
        return 0;
    }

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *cellId = @"ShareSettingCell";
    
    cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"ShareSettingCell" owner:nil options:nil][0];
        
   }
    
    NSUInteger row = [indexPath row];
    UILabel *userlabel = (UILabel *)[cell.contentView viewWithTag:2];
    userlabel.text = catShareService.pageInfo.dataArr[row][@"cid"];
    return cell;


}

#pragma mark - QuestionService Delegate

- (void)didRecieveData{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}
- (void)didRecieveMsg{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}


#pragma mark - Custom Method

-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -IBAction Method

- (IBAction)saveZhanghao:(id)sender {
    
    if (userZhanghaoTF.text.length != 0) {
        [userZhanghaoTF resignFirstResponder];
        [self postAddRequest];
       // [zhanghaoMArr addObject:userZhanghaoTF.text];
        userZhanghaoTF.text=nil;
     
        //[_tableView reloadData];
       
    }
}
//编辑

- (IBAction)Edit:(id)sender {
    UIButton *btn = sender;
    if ([state isEqualToString:@"编辑"]) {
        [_tableView setEditing:YES animated:YES];
        state = @"完成";
        [btn setTitle:state forState:UIControlStateNormal];
    }else{
        recordDic = [NSMutableDictionary dictionary];
        [_tableView setEditing:NO animated:YES];
        state = @"编辑";
        [btn setTitle:state forState:UIControlStateNormal];
    }
}



- (IBAction)deleteZhanghao:(id)sender {
    
    
    NSLog(@"%@",recordDic);
    for (id key in recordDic.allKeys) {
        if (key == recordDic.allKeys[0]) {
            ids = [ids stringByAppendingString:recordDic[key]];
        }else{
        ids = [ids stringByAppendingString:@","];
        ids = [ids stringByAppendingString:recordDic[key]];
        }
    }
    NSLog(@"%@",ids);
    if ([state isEqualToString:@"编辑"]) {
        alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请点击编辑按钮" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    if (recordDic.allKeys.count == 0) {
        alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请选择删除账号或者完成按钮取消编辑" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    [self postDelRequest];
    //状态值初始化
    state = @"编辑";
    [editBtn setTitle:state forState:UIControlStateNormal];
    [_tableView setEditing:NO animated:YES];
}

-(void)postAddRequest{
    // 检查网络
    NSString *mid = nil;
    if (![Constants isExistenceNetwork]) {
        
    } else {
        switch (_mid) {
                //新闻
            case 0:{
                mid = @"1";
            } break;
                //人才
            case 1:{
                 mid = @"2";
            } break;
                //视频
            case 2:{
                 mid = @"3";
            } break;
                //产品
            case 3:{
                 mid = @"4";
            } break;
                //图片
            case 4:{
                 mid = @"5";
            } break;
                //服务
            case 5:{
                 mid = @"6";
            } break;
            default:
                break;
        }
            action = @"gongxiangadd";
            if (!postHud || postHud.hidden == YES) {
                // 提示正在加载数据...
                postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                postHud.labelText = @"正在添加，请稍后...";
            }
            
            addRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
            addRequest.requestMethod = @"POST";
            // 设置超时时间
            addRequest.timeOutSeconds = 60;
            addRequest.delegate = self;
            // 设置参数
            paramsDict = @{@"cid":UID,@"uid":userZhanghaoTF.text,@"mid":mid,@"tid":_tid};//
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
            
            NSData *paramsData = [result toGBKEncodingData];
            addRequest.postBody = [paramsData mutableCopy];
            
            [addRequest startAsynchronous];
        }

}
-(void)postDelRequest{
    // 检查网络
    //ids = @"";
    if (![Constants isExistenceNetwork]) {
        
    } else {
        action = @"gongxiangdel1";
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在删除，请稍后...";
        }
        
        delRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        delRequest.requestMethod = @"POST";
        // 设置超时时间
        delRequest.timeOutSeconds = 60;
        delRequest.delegate = self;
        // 设置参数
        paramsDict = @{@"id":ids};//
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        delRequest.postBody = [paramsData mutableCopy];
        
        [delRequest startAsynchronous];
    }

}

#pragma mark - ASIHttpRequestDelegate method
- (void)requestFinished:(ASIHTTPRequest *)request {
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    NSLog(@"%@",result);
    // 1. 是否解析有错误
    if (!err) {
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            [postHud hide:YES];
            // 提示成功信息
                if (request == addRequest) {
                    [SVProgressHUD showSuccessWithStatus:@"开通成功！"];
                    
                }else{
                    [SVProgressHUD showSuccessWithStatus:@"删除成功！"];
                    ids = @"";
                }
//            [self getDate];
//            [_tableView reloadData];
            [_tableView headerBeginRefreshing];
        } else {
            [postHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"开通失败,请检查账号"];
        }
    } else {
        [postHud hide:YES];
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request {
    
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

//////////////
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
//    
//    NSArray *array=[recordDeleteBtn copy];
//    
//    [tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationFade];
//    [recordDeleteBtn removeAllObjects];
//
//    [_tableView reloadData];
   

   }
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     NSLog(@"%i",indexPath.row);
    NSInteger row = indexPath.row;
    [recordDic setObject:catShareService.pageInfo.dataArr[row][@"id"] forKey:[NSString stringWithFormat:@"%i",row]];
    
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%i",indexPath.row);
    NSInteger row = indexPath.row;
    [recordDic removeObjectForKey:[NSString stringWithFormat:@"%i",row]];
}
#pragma mark - UIAlertViewDelegate
//删除处理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        
    }
}
-(void)alertViewCancel:(UIAlertView *)alertView{
    
}


-(void)dealloc{
    catShareService = nil;
    postHud = nil;
    [addRequest cancel];
    [delRequest cancel];
}

@end
